document.addEventListener('DOMContentLoaded', () => {
    // 只保留账号密码的本地存储
    const storedAccount = localStorage.getItem('zentao_account');
    const storedPassword = localStorage.getItem('zentao_password');

    if (storedAccount) {
        document.getElementById('account').value = storedAccount;
    }
    if (storedPassword) {
        document.getElementById('password').value = storedPassword;
    }
});

function queryProducts() {
    const zentaoUrl = document.getElementById('zentao_url').value;
    const account = document.getElementById('account').value;
    const password = document.getElementById('password').value;

    if (!zentaoUrl || !account || !password) {
        alert('请填写所有必填字段');
        return;
    }

    localStorage.setItem('zentao_account', account);
    localStorage.setItem('zentao_password', password);


    const productListDiv = document.getElementById('product-list');
    productListDiv.innerHTML = '<div class="product-item">查询中...</div>';

    fetch('/query-products', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ zentao_url: zentaoUrl, account, password })
    })
    .then(response => response.json())
    .then(data => {
        let html = '';
        if (data.products && data.products.length > 0) {
            data.products.forEach(product => {
                html += `
                <div class="product-item">
                    <div style="display: flex; justify-content: space-between; align-items: center">
                        <div style="flex:1">
                            <div style="font-size:14px; color:#333; margin-bottom:4px;">${product.name}</div>
                            <div style="font-size:12px; color:#666;">ID: ${product.id}</div>
                        </div>
                        <button style="padding:6px 12px; background:#e9ecef; border-radius:4px; border:none; cursor:pointer"
                                onclick="copyToClipboard('${product.id}')">
                            复制
                        </button>
                    </div>
                </div>`;
            });
        } else {
            html = '<div class="product-item" style="color:#666;">未查询到产品信息</div>';
        }
        productListDiv.innerHTML = html;
    })
    .catch(error => {
        productListDiv.innerHTML = `<div class="product-item" style="color:red;">请求失败：${error.message}</div>`;
    });
}

function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        alert("已成功复制ID: " + text);
    }).catch(err => {
        console.error('复制失败:', err);
        alert("复制失败，请手动选择复制");
    });
}
